import type { AdminLoginResponseDto, AdminUserInfo, TenantInfo } from '@/types/permission';
import request from '@/utils/request';

// 验证码响应类型
export interface CaptchaResponse {
  captchaId: string;
  imageData: string;
}

// 管理员登录请求类型
export interface AdminLoginRequest {
  username: string;
  password: string;
  captchaId: string;
  captchaCode: string;
}

// 管理员登录响应类型 - 前端格式化后的响应
export interface AdminLoginResponse {
  token: string;
  user: AdminUserInfo;
}

// 切换租户请求类型
export interface SwitchTenantRequest {
  tenantId: string;
}

// 切换租户响应类型
export interface SwitchTenantResponse {
  token: string;
  tenant: TenantInfo;
}

// 导出权限相关类型以供其他模块使用
// 同时导出完整的权限相关类型
export { AdminType, PermissionChecker } from '@/types/permission';
export type { AdminUserInfo, TenantInfo };

// 认证API
export const authApi = {
  // 获取验证码
  getCaptcha: async (): Promise<CaptchaResponse> => {
    return await request.get('/admin/auth/captcha');
  },

  // 管理员登录 - 适配新的响应格式
  adminLogin: async (data: AdminLoginRequest): Promise<AdminLoginResponse> => {
    const response: AdminLoginResponseDto = await request.post('/admin/auth/login', data);

    // 将后端响应转换为前端期望的格式
    return {
      token: response.accessToken,
      user: {
        id: response.admin.id,
        username: response.admin.username,
        name: response.admin.name,
        email: response.admin.email,
        phone: response.admin.phone,
        avatar: response.admin.avatar,
        adminType: response.admin.adminType,
        tenantIds: response.admin.tenantIds
      }
    };
  },

  // 退出登录
  logout: async (): Promise<void> => {
    await request.post('/admin/auth/logout');
  },

  // 切换租户 - 针对学校管理员
  switchTenant: async (data: SwitchTenantRequest): Promise<SwitchTenantResponse> => {
    return await request.post('/admin/switch-tenant', data);
  },

  // 获取当前管理员可用的租户列表
  getMyTenants: async (): Promise<TenantInfo[]> => {
    return await request.get('/admin/tenants');
  },

  // 获取当前用户信息
  getUserInfo: async (): Promise<AdminUserInfo> => {
    return await request.get('/admin/auth/me');
  }
};
